# -*- coding: UTF-8 -*-
# @Time    : 2021/7/11 23:30
# @Author  : Sun
# @Email   : xxxxxxxxxxx@xxx.com
# @File    : mitm_rewrite.py
# @software: PyCharm
# 文件注释  :
import json

from mitmproxy import ctx, http

class MitmMapLocal:

    def __init__(self):
        pass

    # 这里相当于方法的重写，函数名字是固定的
    def response(self, flow: http.HTTPFlow):
        if "stock.xueqiu.com/v5/stock/realtime/quotec.json" in flow.request.pretty_url:
            with open(r"./quotec.json", encoding='utf-8') as f:
                # 文本格式打印返回值
                ctx.log.info("Rewrite name返回值" + flow.response.text)
                # ctx.log.info(f.read())
                # 传入本地文件作为返回
                flow.response = http.HTTPResponse.make(
                    # 状态码响应
                    200,
                    # 传入本地文件作为返回
                    f.read()
                )
                # ctx.log.info(flow.response.text)
        if "stock.xueqiu.com/v5/stock/batch/quote.json" in flow.request.pretty_url:
            with open(r"./result.json", encoding='utf-8') as f:
                # 文本格式打印返回值
                ctx.log.info("Rewrite name返回值" + flow.response.text)
                # ctx.log.info(f.read())
                # 传入本地文件作为返回
                flow.response = http.HTTPResponse.make(
                    # 状态码响应
                    200,
                    # 传入本地文件作为返回
                    f.read()
                )


addons = [
    MitmMapLocal()
]


if __name__ == '__main__':
    from mitmproxy.tools.main import mitmdump

    # 使用debug模式启动mitmdump
    # 返回中添加参数--ssl-insecure忽略证书认证报错
    mitmdump(['-p', '8080', '-s', __file__, '--ssl-insecure'])
